<vb>编程,关于多重循环的

来源:百度知道 编辑:UC知道 时间:2024/06/30 15:22:02
#单击窗体产生一个有序数组,并在窗体上打印输出;点击“插入”按钮,要求输入一个数并将其插入数组,使得数组仍然有序(即将该数插入到适当的位置)。
1. 首先定义一个数值类型的数组a()(动态数组),用inputbox函数输入数组元素个数n
2. 利用循环遍历数组,使用数机函数给数组元素赋初值
3. 排序:方法见预习内容的排序算法
输入要插入的数x,重定义动态数组(ReDim Preserve a(n+1) ,增加一个元素);找出要插入的位置p,从数组最后(a(n))到插入位置(a(p))的所有元素逐个后移(nn+1,n-1->n,….p->p+1),然后将x插入位置p(a(p)=x)。

Dim a() As Long
Dim MaxI As Integer

Private Sub Command1_Click()
Dim InsertNum As Long, J As Integer, K As Integer
If MaxI <> 0 Then
InsertNum = CDbl(InputBox("请输入插入数据"))

For J = 0 To MaxI - 1
If InsertNum < a(J) Then

ReDim Preserve a(MaxI)

For K = MaxI - 2 To J Step -1
a(K + 1) = a(K)
Next
a(J) = InsertNum

Exit For
End If
Next

Form1.Refresh
For J = 0 To MaxI - 1
Print a(J)
Next
End If

End Sub

Private Sub Form_Click()
Dim I As Integer, J As Integer, K As Integer, tmp As Double
MaxI = 0
MaxI = CInt(InputBox("请输入数组最大长度"))
If IsNumeric(MaxI) And MaxI <> 0 Then
ReDim a(0 To MaxI - 1)
Randomize
For I = 0 To Max